package org.xlp.db.sql;

import org.xlp.assertion.AssertUtils;
import org.xlp.db.exception.EntityException;
import org.xlp.db.sql.table.Table;
import org.xlp.db.tableoption.xlpenum.DBType;

/**
 * Description: Oracle数据库复杂查询
 * <br/>date: 2024/1/15 17:26
 *
 * @version 1.0
 * @author: xlp
 */
public class OracleComplexQuerySQL extends ComplexQuerySQL{
    /**
     * 私有构造函数
     */
    private OracleComplexQuerySQL(){}

    /**
     * 用实体类构造该对象
     *
     * @param beanClass
     * @return
     * @throws NullPointerException 假如第参数为null，则抛出该异常
     * @throws EntityException
     */
    public static <T> OracleComplexQuerySQL of(Class<T> beanClass){
        return of(beanClass, null);
    }

    /**
     * 用实体类构造该对象
     *
     * @param beanClass
     * @param alias 实体类别名
     * @return
     * @throws NullPointerException 假如第一个参数为null，则抛出该异常
     * @throws EntityException
     */
    public static <T> OracleComplexQuerySQL of(Class<T> beanClass, String alias){
        return of(beanClass, alias, true);
    }

    /**
     * 用实体类构造该对象
     *
     * @param beanClass
     * @param alias 实体类别名
     * @param addTableAliasMapper 标记是否添加表别名与表映射关系， true：添加，false：不添加
     * @return
     * @throws NullPointerException 假如第一个参数为null，则抛出该异常
     * @throws EntityException
     */
    public static <T> OracleComplexQuerySQL of(Class<T> beanClass, String alias,
                                          boolean addTableAliasMapper){
        AssertUtils.isNotNull(beanClass, "beanClass paramter is null!");
        OracleComplexQuerySQL complexQuerySQL = new OracleComplexQuerySQL();
        complexQuerySQL.table = new Table<>(beanClass);
        complexQuerySQL.table.setAlias(alias);
        complexQuerySQL.foreignFields = complexQuerySQL.table.getForeignFields();
        complexQuerySQL.primaryFields = complexQuerySQL.table.getPrimaryFields();
        if (addTableAliasMapper) {
            tableAliasMap(alias, complexQuerySQL);
        }
        return complexQuerySQL;
    }

    @Override
    public Object[] getParams() {
        Object[] params = super.getParams();
        if (getLimit() != null) {
            params[params.length - 2] = getLimit().getStartPos() + 1;
            params[params.length -1] = getLimit().getStartPos() + getLimit().getResultCount();
        }
        return params;
    }

    @Override
    public String getParamSql() {
        return new SQLPartCreator().formatTablePartSql(this, false, DBType.ORACLE_DB);
    }
}
